﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace EssentialWebFramework.Utils
{
    /// <summary>
    /// Enum 工具类 （利用 泛型类 缓存 类型字段等数据）
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class EnumUtils<T>
    {
        /// <summary>
        /// 字段表示类的集合
        /// </summary>
        private static MyFieldInfo[] myFieldInfos;

        /// <summary>
        /// 自定的字段表示类
        /// </summary>
        private class MyFieldInfo
        {
            /// <summary>
            /// FieldInfo 属性
            /// </summary>
            public FieldInfo FieldInfo { get; set; }
            /// <summary>
            /// DescriptionAttribute 属性
            /// </summary>
            public DescriptionAttribute DescriptionAttribute { get; set; }
        }

        /// <summary>
        /// static ctor
        /// </summary>
        static EnumUtils()
        {
            myFieldInfos = typeof(T).GetFields().Select(a =>
            {
                MyFieldInfo myFieldInfo = new MyFieldInfo();
                myFieldInfo.FieldInfo = a;
                object[] tmps = a.GetCustomAttributes(typeof(DescriptionAttribute), false);
                myFieldInfo.DescriptionAttribute = 
                    (tmps == null || tmps.Length == 0) ? null : (DescriptionAttribute)tmps[0];
                return myFieldInfo;
            }).ToArray();
        }

        /// <summary>
        /// 根据枚举值，获取描述
        /// </summary>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        public static string GetEnumDes(T enumValue)
        {
            string value = enumValue.ToString();
            MyFieldInfo field = myFieldInfos.Where(a => a.FieldInfo.Name == value).FirstOrDefault();
            if(field.DescriptionAttribute == null)  //当描述属性没有时，直接返回名称
            {
                return value;
            }
            else
            {
                return field.DescriptionAttribute.Description;
            }
        }
    }
}
